package com.qmock.pay.http;

import org.apache.http.HttpException;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 这个类是一个回调请求的url的httprequest。
 * @author  tianqing.wang
 */
public class AsynHttpMockServer implements AsynMockServer{
    private PayHttpRequest payHttpRequest;
    private Map<String,String> params;
    private String paramURL;
    public AsynHttpMockServer(){
        this.payHttpRequest=new PayHttpRequest();
        this.params=new HashMap<String, String>();
    }
    public AsynHttpMockServer(Map<String,String> params){
        this.payHttpRequest=new PayHttpRequest();
        this.params= params;
    }

    public AsynHttpMockServer(String paramURL){
        this.paramURL=paramURL;
        this.payHttpRequest=new PayHttpRequest();
    }
    public AsynHttpMockServer addParameters(String name,String value){
        this.params.put(name,value);
        return this;
    }
    @Override
    public PayHttpResponse callBack(String baseUrl) {
        if(this.params.size()!=0){
            try {
                PayHttpResponse response= this.payHttpRequest.post(this.params,baseUrl).execute();
                System.out.println(response.getHttpEntity().getContentEncoding());
                return response;
            } catch (HttpException e) {
                e.printStackTrace();
                throw new RuntimeException("在访问"+baseUrl+"的时候，出现了错误，请检查网络连接。");
            }
        }else{
            try {
                PayHttpResponse response= this.payHttpRequest.get(baseUrl).execute();
                this.payHttpRequest.close();
                return response;
            } catch (HttpException e) {
                throw new RuntimeException("在访问"+baseUrl+"的时候，出现了错误，请检查网络连接。");
            }

        }
    }

    public PayHttpResponse callBack(){
        try {
            return this.payHttpRequest.get(this.paramURL).execute();
        } catch (HttpException e) {
            e.printStackTrace();
            throw new RuntimeException("异步回调URL的时候出现了错误");
        }
    }
}
